<template>
  <view class="container">
    <view class="logo">
      婚庆租凭
    </view>
    <button
      class="login-button"
      @click="tapGetUserProfile"
    >
      微信授权登录
    </button>
    <text class="description">
      一键登录，快速体验
    </text>
    <Empower
      ref="popup"
      :show-status="showStatus"
      :user-info="userInfo"
      @sava-info="savaInfo"
    />
  </view>
</template>

<script setup>
import Empower from '../../components/kc-empower/kc-empower.vue'
import { ref, onMounted, nextTick } from 'vue'

const openId = ref('')
const userInfo = ref({
  avatar: '',
  nickName: '',
  phone: ''
})
const showStatus = ref(false)
const popup = ref(null)
const login = () => {
  uni.login({
    provider: 'weixin',
    success: (res) => {
      console.log(res)
      if (res.code) {
        requestLogin(res.code)
      } else {
        uni.showToast({
          title: '登录失败！' + res.errMsg,
          icon: 'none'
        })
      }
    },
    fail: (err) => {
      uni.showToast({
        title: '调用登录接口失败',
        icon: 'none'
      })
    }
  })

  // 调用微信的登录接口
}

onMounted(() => {
  login()
})

const tapGetUserProfile = async () => {
  showStatus.value = true
}
const savaInfo = (data) => {
  // console.log('子组件调用了父组件的方法')
  uni.showLoading(true)
  showStatus.value = false
  userlogin(data.nickName)
}
const requestLogin = (code) => {
  console.log(code)
  http.request({
    url: '/user/getWechatOpenId',
    method: 'POST',
    data: {
      code
    }
  }).then((res) => {
    openId.value = res.data.openid
  })
}
const userlogin = (nickName) => {
  http.request({
    url: '/user/register',
    method: 'POST',
    data: {
      userOpenId: openId.value,
      nickName,
      userName: nickName
    }
  }).then(({ data }) => {
    console.log(data)
    http.loginSuccess(data, () => {
      uni.showLoading(false)
      uni.showToast({
        title: '登录成功',
        icon: 'none',
        complete: () => {
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/index/index'
            })
          }, 1000)
        }
      })
    })
  })
}
onShow(() => {
  // 头部导航标题
  uni.setNavigationBarTitle({
    title: '用户登录'
  })
})
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f0f0;
}

.logo {
  margin-bottom: 40px;
  font-size: 50rpx;
}

.login-button {
  width: 80%;
  height: 50px;
  background-color: #1aad19;
  color: #ffffff;
  border-radius: 25px;
  font-size: 18px;
  text-align: center;
  line-height: 50px;
  margin-bottom: 20px;
}

.description {
  font-size: 14px;
  color: #666;
}
</style>
